import './index.css';
import { useState, useEffect, useRef } from 'react';

type Props = {
   children: React.ReactNode;
   popperContent: React.ReactNode;
   placement?: 'left-bottom' | 'left';
   showConfirm?: boolean;
   onConfirm?: () => void;
};

const MyPopper = ({
   children,
   popperContent,
   placement = 'left-bottom',
   showConfirm = false,
   onConfirm,
}: Props) => {
   const [isOpen, setIsOpen] = useState(false);
   const popperRef = useRef(null);

   const handleOk = () => {
      onConfirm && onConfirm();
      closePopper();
   };
   const closePopper = () => {
      setIsOpen(false);
   };

   const openPopper = (e) => {
      e.stopPropagation();
      setIsOpen(true);
   };

   useEffect(() => {
      const handleClickOutside = (event) => {
         if (popperRef.current && !popperRef.current.contains(event.target)) {
            closePopper();
         }
      };

      document.addEventListener('mousedown', handleClickOutside);
      return () => {
         document.removeEventListener('mousedown', handleClickOutside);
      };
   }, []);

   const cls = 'inline-block relative popper-wrapper ' + placement;

   return (
      <span
         className={cls}
         ref={popperRef}
         onClick={(e) => {
            e.stopPropagation();
         }}
      >
         <span onTouchEnd={openPopper}>
            {children}
         </span>
         {isOpen && (
            <div className="popper">
               <div className="px-2 py-1">{popperContent}</div>
               {showConfirm && (
                  <div className="border-t border-gray-100 p-0.5 flex text-xs text-center">
                     <span
                        className="text-gray-500 grow border-r border-r-gray-100"
                        onClick={closePopper}
                     >
                        取消
                     </span>
                     <span className="text-red-500 grow" onClick={handleOk}>
                        确定
                     </span>
                  </div>
               )}
               <div className="arrow" />
            </div>
         )}
      </span>
   );
};

export default MyPopper;
